#include "enrollwindow.h"
#include <QDebug>
#include <QJsonDocument>
#include <QJsonObject>
#include <QMessageBox>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QPushButton>
#include <QUrl>
#include <QUrlQuery>
#include "EnrollWindow.h"
#include "interfacemanager.h"
#include "ui_enrollwindow.h"

EnrollWindow::EnrollWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::EnrollWindow)
    , manager(new QNetworkAccessManager(this))
{
    ui->setupUi(this);
}

EnrollWindow::~EnrollWindow()
{
    delete ui;
    delete manager;
}

void EnrollWindow::on_toLogButton_clicked()
{
    InterfaceManager::instance()->switchToPage("/MainWindow/First/Log");
}

void EnrollWindow::on_ErollButton_clicked()
{
    // 从 QLineEdit 控件读取数据
    QString username = ui->usernameEdit->text();
    QString password = ui->passwordEdit->text();
    QString email = ui->emailEdit->text();
    QString phone = ui->phoneEdit->text();
    int age = ui->ageEdit->text().toInt();
    QString gender = ui->genderEdit->text();
    QString idNumber = ui->idCardEdit->text();

    // 创建一个 JSON 对象，封装请求体
    QJsonObject json;
    json["username"] = username;
    json["password"] = password;
    json["email"] = email;
    json["phone"] = phone;
    json["age"] = age;
    json["gender"] = gender;
    json["idNumber"] = idNumber;
    json["userLevel"] = 1; // 假设用户级别是 1
    qDebug() << "Preparing request data:" << json;

    // 将 JSON 对象转换为 JSON 文档
    QJsonDocument doc(json);
    QByteArray data = doc.toJson();

    // 设置请求头
    QNetworkRequest request(QUrl("http://127.0.0.1:8080/api/users/register")); // 替换为你的 API URL
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    // 发送 POST 请求
    QNetworkReply *reply = manager->post(request, data);

    // 连接请求完成信号
    connect(reply, &QNetworkReply::finished, this, &EnrollWindow::onRequestFinished);
}

void EnrollWindow::onRequestFinished()
{
    QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());

    // 如果请求失败，输出错误信息
    if (reply->error() != QNetworkReply::NoError) {
        QString errorString = reply->errorString(); // 获取错误信息
        qDebug() << "Request failed with error:" << errorString;
        QMessageBox::critical(this, "Error", "Registration request failed: " + errorString);
        reply->deleteLater();
        return;
    }

    // 请求成功，处理响应数据
    QByteArray response = reply->readAll();
    QJsonDocument doc = QJsonDocument::fromJson(response);
    QJsonObject jsonResponse = doc.object();

    // 处理响应
    int code = jsonResponse["code"].toInt();
    if (code == 200) {
        // 注册成功
        QMessageBox::information(this, "Success", "Registration successful!");
        // 可根据返回的数据进一步处理
        QString userId = jsonResponse["data"].toObject()["id"].toString();
        QString userName = jsonResponse["data"].toObject()["username"].toString();
        QString userEmail = jsonResponse["data"].toObject()["email"].toString();
        // 显示或者使用这些数据
        qDebug() << "User ID: " << userId;
        qDebug() << "Username: " << userName;
        qDebug() << "Email: " << userEmail;
    } else {
        // 注册失败
        QString errorMessage = jsonResponse["message"].toString();
        QMessageBox::warning(this, "Error", "Registration failed: " + errorMessage);
        qDebug() << "Error Message: " << errorMessage;
    }

    // 释放资源
    reply->deleteLater();
}
